package juc.collection;

import cn.hutool.json.JSONUtil;
import io.undertow.util.CopyOnWriteMap;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program: check-repetition
 * @description: 集合线程安全案例
 * @author: hjk
 * @create: 2021-07-12 17:12
 **/
public class NotSafeDemo {
    /**
     * 多个线程同时对集合进行修改,会出现异常，现场不安全
     * @param args
     */
    public static void sss(String[] args) {
        List list = new ArrayList();
        for (int i = 0; i < 100; i++) {
            new Thread(() ->{
                list.add(UUID.randomUUID().toString());
                System.out.println(list.toString());
            }, "线程" + i).start();
        }
    }

    /**
     * vector 实现多个线程同时对集合进行修改
     * @param args
     */
    public static void xxx(String[] args) {
        List list = new Vector();
        for (int i = 0; i < 100; i++) {
            new Thread(() ->{
                list.add(UUID.randomUUID().toString());
                System.out.println(list);
            }, "线程" + i).start();
        }
    }

    /**
     * Collections 转换安全 List 实现多个线程同时对集合进行修改
     * @param args
     */
    public static void qqq(String[] args) {
        List list = Collections.synchronizedList(new ArrayList<>());
        for (int i = 0; i < 100; i++) {
            new Thread(() ->{
                list.add(UUID.randomUUID().toString());
                System.out.println(list);
            }, "线程" + i).start();
        }
    }

    /**
     * 多个线程同时对集合进行修改
     * @param args
     */
    public static void main(String[] args) {
        /**
         * 线程安全List
         */
       List list = new CopyOnWriteArrayList();
        for (int i = 0; i < 100; i++) {
            new Thread(() ->{
                list.add(UUID.randomUUID().toString());
                System.out.println(list);
            }, "线程" + i).start();
        }
        /**
         * 线程安全 map
         */
        Map map = new CopyOnWriteMap();
        for (int i = 0; i < 5; i++) {
            int flag = i;
            new Thread(() ->{
                map.put(UUID.randomUUID().toString(),flag);
                System.out.println(JSONUtil.toJsonStr(map));
            }, "线程" + i).start();
        }
    }
}
